<template>
  <div v-if="isLoginModalVisible" class="login-modal-overlay" @click="handleOverlayClick">
    <div class="login-modal" @click.stop>
      <!-- 关闭按钮 -->
      <!-- <button class="close-btn" @click="handleCloseClick" :disabled="!authStore.isAuthenticated">
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
          <path d="M12 4L4 12M4 4L12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
        </svg>
      </button> -->
      
      <!-- 标题 -->
      <div class="modal-header">
        <h2>{{ isForgotPasswordMode ? (isResetPasswordStep ? '重置密码' : '忘记密码') : (isRegisterMode ? '注册点点清单' : '登录点点清单') }}</h2>
      </div>
      
      <!-- 消息提示 -->
      <div v-if="errorMessage" class="message-toast error">
        {{ errorMessage }}
      </div>
      <div v-if="successMessage" class="message-toast success">
        {{ successMessage }}
      </div>
      
      <!-- 登录/注册方式切换 -->
      <div class="login-tabs" v-if="!isRegisterMode && !isForgotPasswordMode">
        <button 
          :class="['tab-btn', { active: loginMode === 'password' }]"
          @click="setLoginMode('password')"
        >
          密码登录
        </button>
        <button 
          :class="['tab-btn', { active: loginMode === 'sms' }]"
          @click="setLoginMode('sms')"
        >
          验证码登录
        </button>
      </div>
      
      <!-- 登录/注册/忘记密码表单 -->
      <form @submit.prevent="handleSubmit" class="login-form">
        <!-- 注册表单 -->
        <template v-if="isRegisterMode">
          <!-- 用户名 -->
          <div class="form-group">
            <label>用户名</label>
            <input 
              v-model="formData.name"
              type="text"
              placeholder="请输入用户名"
              required
              class="form-input"
            />
          </div>
          
          <!-- 手机号 -->
          <div class="form-group">
            <label>手机号</label>
            <input 
              v-model="formData.phone"
              type="tel"
              placeholder="请输入手机号"
              required
              @blur="handlePhoneBlur"
              maxlength="11"
              class="form-input"
              :class="{ 'error': phoneError }"
            />
            <div v-if="phoneError" class="error-message">{{ phoneError }}</div>
          </div>
          
          <!-- 验证码 -->
          <div class="form-group">
            <label>验证码</label>
            <div class="code-input-group">
              <input 
                v-model="formData.code"
                type="text"
                placeholder="请输入验证码"
                required
                class="form-input code-input"
                maxlength="6"
              />
              <button 
                type="button"
                :disabled="registerCodeCountdown > 0 || !isPhoneValid || isPhoneRegistered === true || isCheckingPhone"
                @click="sendRegisterCode"
                class="send-code-btn"
              >
                {{ isCheckingPhone ? '检查中...' : (registerCodeCountdown > 0 ? `${registerCodeCountdown}秒重发` : '获取验证码') }}
              </button>
            </div>
          </div>
        </template>
        
        <!-- 忘记密码表单 -->
         <template v-else-if="isForgotPasswordMode">
           <!-- 手机号 -->
           <div class="form-group">
             <label>手机号</label>
             <input 
               v-model="formData.phone"
               type="tel"
               placeholder="请输入注册时的手机号"
               required
               @blur="handlePhoneBlur"
               maxlength="11"
               class="form-input"
               :class="{ 'error': phoneError }"
               :disabled="isResetPasswordStep"
             />
             <div v-if="phoneError" class="error-message">{{ phoneError }}</div>
           </div>
           
           <!-- 发送验证码按钮（第一步） -->
           <div v-if="!isResetPasswordStep" class="form-group">
             <button 
               type="button"
               :disabled="!isPhoneValid || resetCodeCountdown > 0 || isPhoneRegistered === false || isCheckingPhone"
               @click="sendResetCode"
               class="send-code-btn full-width"
             >
               {{ isCheckingPhone ? '检查中...' : (resetCodeCountdown > 0 ? `${resetCodeCountdown}秒后重发` : '发送验证码') }}
             </button>
           </div>
           
           <!-- 验证码（重置密码步骤才显示） -->
           <div v-if="isResetPasswordStep" class="form-group">
             <label>验证码</label>
             <input 
               v-model="formData.code"
               type="text"
               placeholder="请输入验证码"
               required
               class="form-input"
               maxlength="6"
             />
           </div>
           
           <!-- 新密码（重置密码步骤才显示） -->
           <div v-if="isResetPasswordStep" class="form-group">
             <label>新密码</label>
             <input 
               v-model="formData.password"
               type="password"
               placeholder="请输入新密码"
               required
               class="form-input"
               :class="{ 'error': passwordError }"
             />
             <div v-if="passwordError" class="error-message">{{ passwordError }}</div>
           </div>
           
           <!-- 确认新密码（重置密码步骤才显示） -->
           <div v-if="isResetPasswordStep" class="form-group">
             <label>确认新密码</label>
             <input 
               v-model="formData.password_confirmation"
               type="password"
               placeholder="请再次输入新密码"
               required
               class="form-input"
               :class="{ 'error': confirmPasswordError }"
             />
             <div v-if="confirmPasswordError" class="error-message">{{ confirmPasswordError }}</div>
           </div>
         </template>
        
        <!-- 登录表单 -->
         <template v-else>
           <!-- 手机号输入（登录时） -->
           <div class="form-group">
             <label>手机号</label>
             <input 
               v-model="formData.username"
               type="tel"
               placeholder="请输入手机号"
               required
               @blur="handlePhoneBlur"
               maxlength="11"
               class="form-input"
               :class="{ 'error': loginPhoneError }"
             />
             <div v-if="loginPhoneError" class="error-message">{{ loginPhoneError }}</div>
           </div>
           
           <!-- 密码输入 -->
           <div v-if="loginMode === 'password'" class="form-group">
             <label>密码</label>
             <input 
               v-model="formData.password"
               type="password"
               placeholder="请输入密码"
               required
               class="form-input"
               :class="{ 'error': passwordError }"
             />
           </div>
           
           <!-- 验证码输入 -->
           <div v-if="loginMode === 'sms'" class="form-group">
             <label>验证码</label>
             <div class="code-input-group">
               <input 
                 v-model="formData.code"
                 type="text"
                 placeholder="请输入验证码"
                 required
                 class="form-input code-input"
                 maxlength="6"
               />
               <button 
                 type="button"
                 :disabled="codeCountdown > 0 || !isLoginPhoneValid || (loginMode === 'sms' && isPhoneRegistered === false) || isCheckingPhone"
                 @click="sendCode"
                 class="send-code-btn"
               >
                 {{ isCheckingPhone ? '检查中...' : (codeCountdown > 0 ? `${codeCountdown}s` : '获取验证码') }}
               </button>
             </div>
           </div>
         </template>
        
        <!-- 注册表单密码字段 -->
        <template v-if="isRegisterMode">
          <!-- 密码输入 -->
          <div class="form-group">
            <label>密码</label>
            <input 
              v-model="formData.password"
              type="password"
              placeholder="请输入密码"
              required
              class="form-input"
              :class="{ 'error': passwordError }"
            />
            <!-- 密码强度提示（仅注册时显示） -->
            <div class="password-strength">
              <div class="strength-bar">
                <div class="strength-fill" :class="passwordStrength.level"></div>
              </div>
              <div class="strength-text">{{ passwordStrength.text }}</div>
              <div v-if="passwordError" class="error-message">{{ passwordError }}</div>
            </div>
          </div>
          
          <!-- 确认密码（注册时） -->
          <div class="form-group">
            <label>确认密码</label>
            <input 
              v-model="formData.password_confirmation"
              type="password"
              placeholder="请再次输入密码"
              required
              class="form-input"
              :class="{ 'error': confirmPasswordError }"
            />
            <div v-if="confirmPasswordError" class="error-message">{{ confirmPasswordError }}</div>
          </div>
        </template>
        
        <!-- 记住我 -->
        <div v-if="loginMode === 'password' && !isRegisterMode && !isForgotPasswordMode" class="form-group checkbox-group">
          <label class="checkbox-label">
            <input v-model="formData.rememberMe" type="checkbox" class="checkbox">
            <span class="checkmark"></span>
            记住我
          </label>
          <a href="#" @click.prevent="toggleForgotPasswordMode" class="forgot-link">忘记密码？</a>
        </div>
        
        <!-- 提交按钮 -->
        <button 
          v-if="!isForgotPasswordMode || isResetPasswordStep"
          type="submit" 
          :disabled="isLoading || !isFormValid"
          class="login-btn"
        >
          <span v-if="isLoading" class="loading-spinner"></span>
          {{ getSubmitButtonText() }}
        </button>
      </form>
      
      <!-- 切换登录/注册/忘记密码 -->
      <div class="register-section">
        <div class="register-link">
          <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
            <path d="M8 1C4.13 1 1 4.13 1 8s3.13 7 7 7 7-3.13 7-7-3.13-7-7-7zm0 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm0 10c-1.75 0-3.29-.73-4.41-1.9.42-.61 1.63-1.1 4.41-1.1s3.99.49 4.41 1.1C11.29 12.27 9.75 13 8 13z" fill="currentColor"/>
          </svg>
          <template v-if="isForgotPasswordMode">
            <a href="#" @click.prevent="backToLogin">返回登录</a>
          </template>
          <template v-else>
            <a href="#" @click.prevent="toggleRegisterMode">
              {{ isRegisterMode ? '已有账号？立即登录' : '没有账号？立即注册' }}
            </a>
          </template>
        </div>
      </div>
      
      <!-- 游客提示 
      <div class="guest-notice">
        <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
          <path d="M8 1C4.13 1 1 4.13 1 8s3.13 7 7 7 7-3.13 7-7-3.13-7-7-7zm1 11H7V7h2v5zm0-6H7V4h2v2z" fill="currentColor"/>
        </svg>
        不登录也可以使用，但最多只能创建3个任务
      </div>
      -->

    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useAuthStore } from '@/stores/authStore'
import api from '@/api/index.js' 

const authStore = useAuthStore()

// 响应式数据
const formData = ref({
  name: '',
  email: '',
  username: '',
  phone: '',
  password: '',
  password_confirmation: '',
  code: '',
  rememberMe: false
})

const codeCountdown = ref(0)
const registerCodeCountdown = ref(0)
const resetCodeCountdown = ref(0)
const isRegisterMode = ref(false)
const isForgotPasswordMode = ref(false)
const isResetPasswordStep = ref(false) // 是否进入重置密码步骤
const errorMessage = ref('')
const successMessage = ref('')
const verificationKey = ref('') // 存储验证码key
const resetVerificationKey = ref('') // 存储重置密码验证码key
const isPhoneRegistered = ref(null) // 添加手机号注册状态
let countdownTimer = null
let registerCountdownTimer = null
let resetCountdownTimer = null
let phoneCheckTimer = null // 防抖定时器
const isCheckingPhone = ref(false) // 手机号检查状态

// 计算属性
const isLoginModalVisible = computed(() => authStore.isLoginModalVisible)
const { isLoading } = authStore
const loginMode = computed(() => authStore.loginMode)

// 手机号验证
const isPhoneValid = computed(() => {
  const phoneRegex = /^1[3-9]\d{9}$/
  return phoneRegex.test(formData.value.phone)
})

const phoneError = computed(() => {
  if (!formData.value.phone) return ''
  
  if (!isPhoneValid.value) {
    return '请输入正确的手机号格式'
  }
  
  // 注册模式下，如果手机号已注册，显示提示
  if (isRegisterMode.value && isPhoneRegistered.value === true) {
    return '该手机号已注册，请直接登录'
  }
  
  // 忘记密码模式下，如果手机号未注册，显示提示
  if (isForgotPasswordMode.value && isPhoneRegistered.value === false) {
    return '该手机号未注册，请先注册'
  }
  
  return ''
})

// 登录时手机号验证
const isLoginPhoneValid = computed(() => {
  const phoneRegex = /^1[3-9]\d{9}$/
  return phoneRegex.test(formData.value.username)
})

const loginPhoneError = computed(() => {
  if (!formData.value.username) return ''
  if (!isLoginPhoneValid.value) return '请输入正确的手机号格式'
  
  // 登录模式下，如果手机号未注册，显示提示
  if (isPhoneRegistered.value === false) {
    return '该手机号未注册，请先注册'
  }
  
  return ''
})

// 密码强度验证
const passwordStrength = computed(() => {
  const password = formData.value.password
  if (!password) return { level: 'none', text: '请输入密码' }
  
  if (password.length < 6) {
    return { level: 'weak', text: '密码长度至少6位' }
  }
  
  const hasNumber = /\d/.test(password)
  const hasLetter = /[a-zA-Z]/.test(password)
  const hasSpecial = /[!@#$%^&*(),.?":{}|<>]/.test(password)
  
  if (hasNumber && hasLetter && hasSpecial) {
    return { level: 'strong', text: '密码强度：强' }
  } else if (hasNumber && hasLetter) {
    return { level: 'medium', text: '密码强度：中等' }
  } else {
    return { level: 'weak', text: '密码需包含数字和字母' }
  }
})

const passwordError = computed(() => {
  if (!formData.value.password) return ''
  if (formData.value.password.length < 6) return '密码长度至少6位'
  if (!/\d/.test(formData.value.password) || !/[a-zA-Z]/.test(formData.value.password)) {
    return '密码必须包含数字和字母'
  }
  return ''
})

const confirmPasswordError = computed(() => {
  if (!formData.value.password_confirmation) return ''
  if (formData.value.password !== formData.value.password_confirmation) {
    return '两次输入的密码不一致'
  }
  return ''
})

const isFormValid = computed(() => {
  if (isRegisterMode.value) {
    return formData.value.name && 
           isPhoneValid.value && 
           formData.value.code &&
           formData.value.password && 
           formData.value.password_confirmation &&
           formData.value.password === formData.value.password_confirmation &&
           !passwordError.value
  }
  
  if (isForgotPasswordMode.value) {
    if (isResetPasswordStep.value) {
      // 重置密码步骤：需要验证码和新密码
      return formData.value.code &&
             formData.value.password &&
             formData.value.password_confirmation &&
             formData.value.password === formData.value.password_confirmation &&
             !passwordError.value
    } else {
      // 发送验证码步骤：只需要手机号
      return isPhoneValid.value
    }
  }
  
  if (loginMode.value === 'password') {
    return isLoginPhoneValid.value && formData.value.password
  } else {
    return isLoginPhoneValid.value && formData.value.code
  }
})

// 方法
const { hideLoginModal, setLoginMode } = authStore

// 处理遮罩点击
const handleOverlayClick = () => {
  // 如果用户未登录，不允许关闭弹窗
  if (authStore.isAuthenticated) {
    hideLoginModal()
  }
}

// 处理关闭按钮点击
const handleCloseClick = () => {
  // 如果用户未登录，不允许关闭弹窗
  if (authStore.isAuthenticated) {
    hideLoginModal()
  }
}

// 切换注册模式
const toggleRegisterMode = () => {
  isRegisterMode.value = !isRegisterMode.value
  isForgotPasswordMode.value = false
  isResetPasswordStep.value = false
  clearForm()
}

const toggleForgotPasswordMode = () => {
  isForgotPasswordMode.value = !isForgotPasswordMode.value
  isRegisterMode.value = false
  isResetPasswordStep.value = false
  clearForm()
}

const backToLogin = () => {
  isForgotPasswordMode.value = false
  isRegisterMode.value = false
  isResetPasswordStep.value = false
  clearForm()
}

// 清空表单
const clearForm = () => {
  formData.value = {
    name: '',
    email: '',
    username: '',
    phone: '',
    password: '',
    password_confirmation: '',
    code: '',
    rememberMe: false
  }
  verificationKey.value = ''
  resetVerificationKey.value = ''
  errorMessage.value = ''
  successMessage.value = ''
  isPhoneRegistered.value = null // 重置手机号注册状态
  
  // 清除倒计时
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
  if (registerCountdownTimer) {
    clearInterval(registerCountdownTimer)
    registerCountdownTimer = null
  }
  if (resetCountdownTimer) {
    clearInterval(resetCountdownTimer)
    resetCountdownTimer = null
  }
  codeCountdown.value = 0
  registerCodeCountdown.value = 0
  resetCodeCountdown.value = 0
  
  // 清除防抖定时器
  if (phoneCheckTimer) {
    clearTimeout(phoneCheckTimer)
    phoneCheckTimer = null
  }
  isCheckingPhone.value = false
}

// 实时验证手机号注册状态（防抖处理）
const checkPhoneWithDebounce = async (phone, isLoginMode = false) => {
  if (phoneCheckTimer) {
    clearTimeout(phoneCheckTimer)
  }
  
  phoneCheckTimer = setTimeout(async () => {
    if (!phone || !(isLoginMode ? isLoginPhoneValid.value : isPhoneValid.value)) {
      isPhoneRegistered.value = null
      return
    }
    
    isCheckingPhone.value = true
    try {
      const isRegistered = await checkPhoneRegistered(phone)
      isPhoneRegistered.value = isRegistered
    } catch (error) {
      console.error('检查手机号失败:', error)
      isPhoneRegistered.value = null
    } finally {
      isCheckingPhone.value = false
    }
  }, 500) // 500ms防抖延迟
}

// 监听手机号变化（注册和忘记密码模式）
watch(() => formData.value.phone, (newPhone) => {
  if (isRegisterMode.value || isForgotPasswordMode.value) {
    checkPhoneWithDebounce(newPhone)
  }
})

// 监听登录手机号变化
watch(() => formData.value.username, (newUsername) => {
  if (!isRegisterMode.value && !isForgotPasswordMode.value) {
    checkPhoneWithDebounce(newUsername, true)
  }
})

// 监听模式切换，重置手机号状态
watch([isRegisterMode, isForgotPasswordMode], () => {
  isPhoneRegistered.value = null
  if (phoneCheckTimer) {
    clearTimeout(phoneCheckTimer)
    phoneCheckTimer = null
  }
  isCheckingPhone.value = false
})

// 发送注册验证码
const sendRegisterCode = async () => {
  if (!isPhoneValid.value) {
    showError('请输入正确的手机号')
    return
  }
  
  try {
    const response = await api.post('/verificationCodes', { // 修改：使用api实例，去掉/api/v1前缀
      phone: formData.value.phone,
      type: 'register'
    })
    
    if (response.data.success) {
      verificationKey.value = response.data.data.key
      
      // 开始倒计时
      registerCodeCountdown.value = 60
      registerCountdownTimer = setInterval(() => {
        registerCodeCountdown.value--
        if (registerCodeCountdown.value <= 0) {
          clearInterval(registerCountdownTimer)
          registerCountdownTimer = null
        }
      }, 1000)
      
      // 开发环境显示验证码
      if (response.data.debug_code) {
        showSuccess(`验证码发送成功！开发环境验证码：${response.data.debug_code}`)
      } else {
        showSuccess('验证码发送成功！')
      }
    }
  } catch (error) {
    const errorMsg = error.response?.data?.error || '验证码发送失败，请重试'
    showError(errorMsg)
  }
}

// 发送登录验证码
const sendCode = async () => {
  if (!formData.value.username) {
    showError('请先输入手机号')
    return
  }
  
  if (!isLoginPhoneValid.value) {
    showError('请输入正确的手机号格式')
    return
  }
  
  try {
    const response = await api.post('/verificationCodes', { // 修改：使用api实例，去掉/api/v1前缀
      phone: formData.value.username,
      type: 'login'
    })
    
    if (response.data.success) {
      verificationKey.value = response.data.data.key
      
      // 开始倒计时
      codeCountdown.value = 60
      countdownTimer = setInterval(() => {
        codeCountdown.value--
        if (codeCountdown.value <= 0) {
          clearInterval(countdownTimer)
          countdownTimer = null
        }
      }, 1000)
      
      // 开发环境显示验证码
      if (response.data.debug_code) {
        showSuccess(`验证码发送成功！开发环境验证码：${response.data.debug_code}`)
      } else {
        showSuccess('验证码发送成功！')
      }
    }
  } catch (error) {
    const errorMsg = error.response?.data?.error || '验证码发送失败，请重试'
    showError(errorMsg)
  }
}

// 检查手机号是否已注册
const checkPhoneRegistered = async (phone) => {
  if (!phone) {
    return null
  }
  
  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(phone)) {
    return null
  }
  
  try {
    const response = await api.post('/check-phone', {
      phone: phone
    })
    
    if (response.data.success) {
      return response.data.data.is_registered
    }
  } catch (error) {
    console.error('检查手机号失败:', error)
    return null
  }
}

// 手机号输入框失去焦点时的处理（优化后主要用于立即验证）
const handlePhoneBlur = async () => {
  // 注册模式下检查手机号
  if (isRegisterMode.value) {
    if (formData.value.phone && isPhoneValid.value) {
      // 清除防抖定时器，立即检查
      if (phoneCheckTimer) {
        clearTimeout(phoneCheckTimer)
        phoneCheckTimer = null
      }
      
      isCheckingPhone.value = true
      try {
        const isRegistered = await checkPhoneRegistered(formData.value.phone)
        isPhoneRegistered.value = isRegistered
      } catch (error) {
        console.error('检查手机号失败:', error)
        isPhoneRegistered.value = null
      } finally {
        isCheckingPhone.value = false
      }
    }
    return
  }
  
  // 忘记密码模式下检查手机号
  if (isForgotPasswordMode.value) {
    if (formData.value.phone && isPhoneValid.value) {
      // 清除防抖定时器，立即检查
      if (phoneCheckTimer) {
        clearTimeout(phoneCheckTimer)
        phoneCheckTimer = null
      }
      
      isCheckingPhone.value = true
      try {
        const isRegistered = await checkPhoneRegistered(formData.value.phone)
        isPhoneRegistered.value = isRegistered
        
        if (isRegistered === false) {
          showError('该手机号未注册，请先注册')
        }
      } catch (error) {
        console.error('检查手机号失败:', error)
        isPhoneRegistered.value = null
      } finally {
        isCheckingPhone.value = false
      }
    }
    return
  }
  
  // 登录模式下检查手机号
  if (formData.value.username && isLoginPhoneValid.value) {
    // 清除防抖定时器，立即检查
    if (phoneCheckTimer) {
      clearTimeout(phoneCheckTimer)
      phoneCheckTimer = null
    }
    
    isCheckingPhone.value = true
    try {
      const isRegistered = await checkPhoneRegistered(formData.value.username)
      isPhoneRegistered.value = isRegistered
      
      if (isRegistered === false) {
        showError('该手机号未注册，请先注册')
      }
    } catch (error) {
      console.error('检查手机号失败:', error)
      isPhoneRegistered.value = null
    } finally {
      isCheckingPhone.value = false
    }
  }
}

// 处理注册
const handleRegister = async () => {
  try {
    authStore.setLoading(true)
    
    const response = await api.post('/register', {
      name: formData.value.name,
      phone: formData.value.phone,
      verification_code: formData.value.code,
      verification_key: verificationKey.value,
      password: formData.value.password,
      password_confirmation: formData.value.password_confirmation
    })
    
    if (response.data.success && response.data.data) {
      // 使用统一的登录成功处理方法
      await authStore.handleLoginSuccess(response.data.data.access_token, response.data.data.user)
      
      // 清空表单
      clearForm()
    }
  } catch (error) {
    const errorMsg = error.response?.data?.error || error.response?.data?.message || '注册失败，请重试'
    showError(errorMsg)
  } finally {
    authStore.setLoading(false)
  }
}

// 处理登录
const handleLogin = async () => {
  try {
    authStore.setLoading(true)
    
    let response
    
    if (loginMode.value === 'password') {
      response = await api.post('/login/password', { // 修改：使用api实例，去掉/api/v1前缀
        username: formData.value.username,
        password: formData.value.password,
        remember_me: formData.value.rememberMe
      })
    } else {
      response = await api.post('/login/sms', { // 修改：使用api实例，去掉/api/v1前缀
        phone: formData.value.username,
        code: formData.value.code,
        verification_key: verificationKey.value
      })
    }
    
    if (response.data.success && response.data.data) {
      // 使用统一的登录成功处理方法
      await authStore.handleLoginSuccess(response.data.data.access_token, response.data.data.user)
      
      // 清空表单
      clearForm()
    }
  } catch (error) {
    const errorMsg = error.response?.data?.error || '登录失败，请重试'
    showError(errorMsg)
  } finally {
    authStore.setLoading(false)
  }
}

// 显示错误信息
const showError = (message) => {
  successMessage.value = '' // 清除成功消息
  errorMessage.value = message
  setTimeout(() => {
    errorMessage.value = ''
  }, 5000)
}

// 显示成功信息
const showSuccess = (message) => {
  errorMessage.value = '' // 清除错误消息
  successMessage.value = message
  setTimeout(() => {
    successMessage.value = ''
  }, 3000)
}

// 获取提交按钮文本
const getSubmitButtonText = () => {
  if (isLoading.value) {
    if (isRegisterMode.value) return '注册中...'
    if (isForgotPasswordMode.value) {
      return isResetPasswordStep.value ? '重置中...' : '发送中...'
    }
    return '登录中...'
  }
  
  if (isRegisterMode.value) return '注册'
  if (isForgotPasswordMode.value) {
    return isResetPasswordStep.value ? '重置密码' : '发送验证码'
  }
  return '登录'
}

// 发送重置密码验证码
const sendResetCode = async () => {
  if (!isPhoneValid.value) {
    showError('请输入正确的手机号')
    return
  }
  
  if (isPhoneRegistered.value === false) {
    showError('该手机号未注册，请先注册')
    return
  }
  
  try {
    const response = await api.post('/reset-password/send-code', {
      phone: formData.value.phone
    })
    
    if (response.data.success) {
      resetVerificationKey.value = response.data.data.key
      
      // 开始倒计时
      resetCodeCountdown.value = 60
      resetCountdownTimer = setInterval(() => {
        resetCodeCountdown.value--
        if (resetCodeCountdown.value <= 0) {
          clearInterval(resetCountdownTimer)
          resetCountdownTimer = null
        }
      }, 1000)
      
      // 开发环境显示验证码
      if (response.data.debug_code) {
        showSuccess(`验证码发送成功！开发环境验证码：${response.data.debug_code}`)
      } else {
        showSuccess('验证码发送成功！')
      }
      
      // 进入重置密码步骤
      isResetPasswordStep.value = true
    }
  } catch (error) {
    const errorMsg = error.response?.data?.error || '验证码发送失败，请重试'
    showError(errorMsg)
  }
}

// 处理重置密码
const handleResetPassword = async () => {
  try {
    authStore.setLoading(true)
    
    const response = await api.post('/reset-password', {
      phone: formData.value.phone,
      verification_code: formData.value.code,
      verification_key: resetVerificationKey.value,
      password: formData.value.password,
      password_confirmation: formData.value.password_confirmation
    })
    
    if (response.data.success) {
      showSuccess('密码重置成功，请使用新密码登录')
      
      // 延迟后返回登录页面
      setTimeout(() => {
        backToLogin()
      }, 2000)
    }
  } catch (error) {
    const errorMsg = error.response?.data?.error || error.response?.data?.message || '密码重置失败，请重试'
    showError(errorMsg)
  } finally {
    authStore.setLoading(false)
  }
}

// 处理表单提交
const handleSubmit = async () => {
  if (isRegisterMode.value) {
    await handleRegister()
  } else if (isForgotPasswordMode.value) {
    if (isResetPasswordStep.value) {
      await handleResetPassword()
    } else {
      await sendResetCode()
    }
  } else {
    await handleLogin()
  }
}

// 清理定时器
onUnmounted(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
  if (registerCountdownTimer) {
    clearInterval(registerCountdownTimer)
  }
  if (resetCountdownTimer) {
    clearInterval(resetCountdownTimer)
  }
})
</script>

<style lang="less" scoped>
.login-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(4px);
}

.login-modal {
  background: var(--surface-color);
  border-radius: 12px;
  width: 400px;
  max-width: 90vw;
  max-height: 90vh;
  overflow-y: auto;
  position: relative;
  box-shadow: var(--shadow-color);
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.close-btn {
  position: absolute;
  top: 16px;
  right: 16px;
  background: none;
  border: none;
  cursor: pointer;
  padding: 8px;
  border-radius: 6px;
  color: var(--text-secondary);
  transition: all 0.2s;
  
  &:hover:not(:disabled) {
    background: var(--surface-color);
    color: var(--text-primary);
  }
  
  &:disabled {
    opacity: 0.3;
    cursor: not-allowed;
  }
}

.modal-header {
  padding: 32px 32px 24px;
  text-align: center;
  
  h2 {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: var(--text-primary);
  }
}

.login-tabs {
  display: flex;
  margin: 0 32px 24px;
  background: var(--surface-color);
  border-radius: 8px;
  padding: 4px;
}

.tab-btn {
  flex: 1;
  padding: 8px 16px;
  border: none;
  background: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  color: var(--text-secondary);
  transition: all 0.2s;
  
  &.active {
    background: var(--background-color);
    color: var(--primary-color);
    border: 1px solid var(--primary-color);
    box-shadow: var(--shadow-color);
  }
}

.login-form {
  padding: 0 32px;
}

.form-group {
  margin-bottom: 20px;
  
  label {
    display: flex;
    margin-bottom: 6px;
    font-size: 14px;
    font-weight: 500;
    color: var(--text-primary);
  }
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  font-size: 14px;
  transition: all 0.2s;
  box-sizing: border-box;
  
  &:focus {
    outline: none;
    border-color: var(--primary-color);
    box-shadow: 0 0 0 3px rgba(var(--primary-color), 0.1);
  }
  
  &::placeholder {
    color: var(--text-secondary);
  }
}

.code-input-group {
  display: flex;
  gap: 8px;
}

.code-input {
  flex: 1;
}

.send-code-btn {
  padding: 12px 16px;
  border: 1px solid var(--primary-color);
  background: var(--surface-color);
  color: var(--primary-color);
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.2s;
  
  &:hover:not(:disabled) {
    background: var(--primary-hover);
    color: var(--surface-color);
  }
  
  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
  
  &.full-width {
    width: 100%;
    margin-top: 8px;
  }
}

.checkbox-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  font-size: 14px;
  color: var(--text-primary);
}

.checkbox {
  display: none;
}

.checkmark {
  width: 16px;
  height: 16px;
  border: 2px solid var(--border-color);
  border-radius: 4px;
  margin-right: 8px;
  position: relative;
  transition: all 0.2s;
}

.checkmark::after {
  content: '';
  position: absolute;
  left: 4px;
  top: 1px;
  width: 4px;
  height: 8px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
  opacity: 0;
  transition: opacity 0.2s;
}

.checkbox:checked + .checkmark {
  background: var(--primary-color);
  border-color: var(--primary-color);
}

.checkbox:checked + .checkmark::after {
  opacity: 1;
}

.forgot-link {
  color: var(--primary-color);
  text-decoration: none;
  font-size: 14px;
  
  &:hover {
    text-decoration: underline;
  }
}

.login-btn {
  width: 100%;
  padding: 12px;
  background: var(--primary-color);
  color: var(--surface-color);
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  
  &:hover:not(:disabled) {
    background: var(--primary-hover);
  }
  
  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.register-section {
  padding: 24px 0 32px 0;
  text-align: center;
}

.register-link {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  color: var(--primary-color);
  text-decoration: none;
  font-size: 14px;
  
  a {
    color: inherit;
    text-decoration: none;
    
    &:hover {
      text-decoration: underline;
    }
  }
}

.guest-notice {
  margin: 16px 32px;
  padding: 12px;
  background: var(--background-color);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: var(--text-secondary);
}



.message-toast {
  margin: 0 32px 16px;
  padding: 12px 16px;
  border-radius: 8px;
  font-size: 14px;
  animation: slideDown 0.3s ease-out;
  
  &.error {
    background: #fee;
    border: 1px solid #fcc;
    color: #c33;
  }
  
  &.success {
    background: #efe;
    border: 1px solid #cfc;
    color: #363;
  }
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.form-input.error {
  border-color: #f56565;
  box-shadow: 0 0 0 3px rgba(245, 101, 101, 0.1);
}

.error-message {
  margin-top: 6px;
  font-size: 12px;
  color: #f56565;
}

.password-strength {
  margin-top: 8px;
}

.strength-bar {
  width: 100%;
  height: 4px;
  background: #e2e8f0;
  border-radius: 2px;
  overflow: hidden;
  margin-bottom: 6px;
}

.strength-fill {
  height: 100%;
  transition: all 0.3s ease;
  
  &.weak {
    width: 33%;
    background: #f56565;
  }
  
  &.medium {
    width: 66%;
    background: #ed8936;
  }
  
  &.strong {
    width: 100%;
    background: #48bb78;
  }
  
  &.none {
    width: 0%;
    background: #e2e8f0;
  }
}

.strength-text {
  font-size: 12px;
  color: var(--text-secondary);
  margin-bottom: 4px;
}
</style>